package m

import (
	"GameServer/Common/utils"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"

	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"
)

// 测试活动奖励
type TestActivityRes struct {
	BaseM
	Uid      bson.ObjectId `bson:"_id" json:"uid"`
	SendTime int64         `bson:"sendTime" json:"sendTime"`
}

func NewTestActivityRes() cache.EntryI {
	return &TestActivityRes{SendTime: 0}
}

// 保存信息
func (uTestActivityRes *TestActivityRes) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("testActivityRes", bson.M{"_id": uTestActivityRes.Uid}, uTestActivityRes)
	if err != nil {
		return
	}
	return
}

func (uTestActivityRes *TestActivityRes) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		uTestActivityRes.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		uTestActivityRes.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "TestActivityRes_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return uTestActivityRes.LoadData()
}

// 加载数据
func (uTestActivityRes *TestActivityRes) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("testActivityRes", bson.M{"_id": uTestActivityRes.Uid}, nil, &uTestActivityRes)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	return
}

// 更新数据
func (uTestActivityRes *TestActivityRes) Update(val *TestActivityRes) {
	Cache.Put("testActivityRes", uTestActivityRes.Uid.Hex(), val)
	val.UpdateData()
}

// 当天是否发送过
func (uTestActivityRes *TestActivityRes) IsSend() bool {
	if uTestActivityRes.SendTime == 0 {
		return false
	}
	now := utils.TNow()
	old := utils.TTime(uTestActivityRes.SendTime, 0)
	if now.Year() == old.Year() && now.Month() == old.Month() && now.Day() == old.Day() {
		return true
	}
	return false
}

// 设置当前时间为发送时间
func (uTestActivityRes *TestActivityRes) SetSentTime() {
	defer uTestActivityRes.UpdateData()
	uTestActivityRes.SendTime = utils.TNow().Unix()
}

//
func (u *User) GetTestActivityRes() (r *TestActivityRes) {
	v, _ := Cache.Get("testActivityRes", u.Uid.Hex())
	return v.(*TestActivityRes)
}
